﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;

namespace DBMigrator.Core.Execution
{
    public class ConsoleMigrationRunner
    {
        private DateTime? Version { get; set; }
        private string Environment { get; set; }

        public ConsoleMigrationRunner(List<string> args)
        {
            InitArguments();
            ParseArguments(args);
        }

        public void ExecuteMigrations()
        {
            var migrator = new Migrator(Assembly.GetCallingAssembly(), Environment);

            if(Version.HasValue)
            {
                migrator.MigrateTo(Version.Value);
            }
            else
            {
                migrator.MigrateToLatest();
            }
        }

        private void InitArguments()
        {
            Environment = ConfigurationManager.AppSettings["DefaultEnvironment"];
        }

        private void ParseArguments(List<string> args)
        {
            while (args.Count > 0)
            {
                if(args[0] == "-v")
                {
                    Version = DateTime.Parse(GetArgument(args));
                }
                else if(args[0] == "-e")
                {
                    Environment = GetArgument(args);
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Unknown command line argument {0}", args[0]));
                }
            }
        }

        private static string GetArgument(List<string> args)
        {
            var argument = args[1];
            args.RemoveRange(0, 2);
            return argument;
        }
    }
}
